import plugin from '../../lib/plugins/plugin.js';
import { Restart } from '../other/restart.js';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

// 动态获取当前文件所在目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export class FengyunManager extends plugin {
  constructor() {
    super({
      name: '风云插件管理器',
      dsc: '风云插件的更新和推送管理',
      event: 'message',
      priority: 5000,
      rule: [
        {
          reg: '^#风云更新fq$',
          fnc: 'handleUpdate',
          permission: 'master'
        },
        {
          reg: '^#风云强制更新fq$',
          fnc: 'handleForceUpdate',
          permission: 'master'
        },
        {
          reg: '^#风云推送(?:\\s+(.+))?$',
          fnc: 'handlePush',
          permission: 'master'
        },
        {
          reg: '^#风云推送状态$',
          fnc: 'checkPushStatus',
          permission: 'master'
        },
        {
          reg: '^#风云推送帮助$',
          fnc: 'showHelp',
          permission: 'master'
        },
        {
          reg: '^#风云强制推送$',
          fnc: 'handleForcePush',
          permission: 'master'
        },
        // 新增：GitCode 调试命令
        {
          reg: '^#风云调试推送$',
          fnc: 'debugGitCodePush',
          permission: 'master'
        }
      ]
    });

    // 动态配置信息 - 多仓库支持
    this.config = {
      // 动态获取插件目录
      pluginDir: this.getPluginRootDir(),
      // 多仓库配置
      repos: {
        gitcode: {
          url: 'https://gitcode.com/fengyunnb_admin/fengyun-plugin.git',
          token: '2JXcRJSH4jREqio-f2xFw45s', // 请替换为实际的gitcode token
          name: 'GitCode'
        },
        gitee: {
          url: 'https://gitee.com/fengyunnb/fengyun-plugin.git',
          token: 'aa89212a2688c4875a265557a42fe064',
          name: 'Gitee'
        }
      },
      branch: 'main',
      // 默认更新源（优先使用gitcode）
      defaultUpdateSource: 'Gitee'
    };

    // 授权用户
    this.authorizedUser = '3669962171';
    
    // 日志前缀
    this.logPrefix = ' ';
    
    console.log(`${this.logPrefix} 插件目录: ${this.config.pluginDir}`);
    console.log(`${this.logPrefix} 配置仓库: GitCode(更新优先) + Gitee(推送备份)`);
  }

  // ========== 动态获取插件根目录 ==========
  getPluginRootDir() {
    try {
      // 方法1: 从当前文件路径推断
      let currentDir = __dirname;
      
      // 向上查找直到找到plugins目录
      while (currentDir && !currentDir.endsWith('plugins')) {
        const parentDir = dirname(currentDir);
        if (parentDir === currentDir) break; // 到达根目录
        currentDir = parentDir;
      }
      
      if (currentDir.endsWith('plugins')) {
        // 在plugins目录下寻找风云插件目录
        const possibleDirs = [
          join(currentDir, 'fengyun-plugin'),
          join(currentDir, 'fengyun-plugins'),
          join(currentDir, 'fengyun-plugin')
        ];
        
        for (const dir of possibleDirs) {
          try {
            const fs = require('fs');
            if (fs.existsSync(dir)) {
              return dir;
            }
          } catch (e) {
            // 忽略错误，继续检查下一个
          }
        }
        
        // 如果都没找到，使用第一个可能的目录
        return possibleDirs[0];
      }
      
      // 方法2: 使用进程工作目录
      return join(process.cwd(), 'plugins', 'fengyun-plugins');
      
    } catch (error) {
      console.error(`${this.logPrefix} 获取插件目录失败:`, error);
      // 回退到相对路径
      return './plugins/fengyun-plugins';
    }
  }

  // ========== 权限检查 ==========
  checkAuthPermission(e) {
    return String(e.user_id) === this.authorizedUser;
  }

  // ========== 强制更新功能 ==========
  async handleForceUpdate(e) {
    try {
      await this.sendNoteWithRetry(e, '🚨 开始强制更新风云插件...\n⚠️ 注意：这将丢弃所有本地修改！', 2);

      const result = await this.executeForceUpdate();
      
      if (!result.success) {
        await this.sendNoteWithRetry(e, `❌ 强制更新失败：${result.error}`, 2);
        return false;
      }

      const noteMsg = `✅ 风云插件强制更新完成\n📝 ${result.message}\n⏰ ${new Date().toLocaleString('zh-CN')}`;
      await this.sendNoteWithRetry(e, noteMsg, 2);
      
      // 重启应用
      await this.restartWithRestart(e);
      
      return true;

    } catch (error) {
      await this.sendNoteWithRetry(e, `❌ 强制更新异常：${error.message}`, 2);
      return false;
    }
  }

  // ========== 执行强制更新 ==========
  async executeForceUpdate() {
    try {
      const fs = await import('fs/promises');
      
      // 检查目录是否存在
      try {
        await fs.access(this.config.pluginDir);
      } catch {
        return { success: false, error: '插件目录不存在: ' + this.config.pluginDir };
      }

      // 检查是否是Git仓库
      if (!await this.isGitRepository()) {
        return { 
          success: false, 
          error: '当前目录不是Git仓库，无法强制更新' 
        };
      }

      // 保存当前状态信息
      const currentBranch = await this.getCurrentBranch();
      const hasChanges = await this.hasLocalChanges();
      
      let message = '';
      if (hasChanges) {
        message += `🗑️ 已丢弃 ${await this.getChangedFilesCount()} 个文件的本地修改\n`;
      }

      // 强制重置到远程仓库
      await this.setupMultipleRemotes();

      let updateSuccess = false;
      let updateSource = this.config.defaultUpdateSource;
      
      try {
        // 尝试从默认源强制更新
        const authUrl = this.getAuthUrl(this.config.defaultUpdateSource);
        await this.runGitCommand(`fetch ${this.config.defaultUpdateSource}`);
        await this.runGitCommand(`reset --hard ${this.config.defaultUpdateSource}/${this.config.branch}`);
        updateSuccess = true;
        message += `🔄 从 ${this.config.repos[this.config.defaultUpdateSource].name} 强制更新成功\n`;
      } catch (error) {
        console.log(`${this.logPrefix} GitCode强制更新失败，尝试Gitee:`, error.message);
        try {
          // 尝试从备用源强制更新
          await this.runGitCommand('fetch gitee');
          await this.runGitCommand('reset --hard gitee/main');
          updateSuccess = true;
          updateSource = 'gitee';
          message += `🔄 从 ${this.config.repos.gitee.name} 强制更新成功\n`;
        } catch (fallbackError) {
          return { 
            success: false, 
            error: `强制更新失败: ${error.message} | 备用更新也失败: ${fallbackError.message}` 
          };
        }
      }
      
      if (!updateSuccess) {
        return { success: false, error: '所有更新源均失败' };
      }

      // 获取更新日志
      const newCommit = await this.getCurrentCommit();
      message += `📝 当前提交: ${newCommit ? newCommit.substring(0, 8) : '未知'}\n`;
      message += `🌿 分支: ${currentBranch}`;

      return { 
        success: true, 
        message,
        updateSource 
      };

    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // ========== 获取当前分支 ==========
  async getCurrentBranch() {
    try {
      const result = await this.runGitCommand('branch --show-current');
      return result.success ? result.stdout : '未知';
    } catch {
      return '未知';
    }
  }

  // ========== 检查是否有本地修改 ==========
  async hasLocalChanges() {
    try {
      const result = await this.runGitCommand('status --porcelain');
      return result.success && result.stdout.trim().length > 0;
    } catch {
      return false;
    }
  }

  // ========== 获取修改文件数量 ==========
  async getChangedFilesCount() {
    try {
      const result = await this.runGitCommand('status --porcelain');
      if (result.success && result.stdout.trim()) {
        return result.stdout.split('\n').length;
      }
      return 0;
    } catch {
      return 0;
    }
  }

  // ========== GitCode 推送调试 ==========
  async debugGitCodePush(e) {
    if (!this.checkAuthPermission(e)) {
      return false;
    }

    try {
      await e.reply('🔍 开始诊断 GitCode 推送问题...');
      
      const debugResults = [];
      
      // 1. 检查目录和 Git 状态
      debugResults.push('=== 基础状态检查 ===');
      const fs = await import('fs/promises');
      try {
        await fs.access(this.config.pluginDir);
        debugResults.push('✅ 插件目录存在');
      } catch {
        debugResults.push('❌ 插件目录不存在');
        await e.reply(debugResults.join('\n'));
        return;
      }

      // 2. 检查 Git 仓库
      const isGitRepo = await this.isGitRepository();
      debugResults.push(isGitRepo ? '✅ Git 仓库已初始化' : '❌ Git 仓库未初始化');
      
      if (isGitRepo) {
        // 3. 检查分支
        const branchResult = await this.runGitCommand('branch --show-current');
        debugResults.push(`🌿 当前分支: ${branchResult.success ? branchResult.stdout : '未知'}`);
        
        // 4. 检查远程仓库配置
        debugResults.push('\n=== 远程仓库配置检查 ===');
        for (const [repoKey, repoConfig] of Object.entries(this.config.repos)) {
          const remoteResult = await this.runGitCommand(`remote get-url ${repoKey}`);
          if (remoteResult.success) {
            debugResults.push(`✅ ${repoConfig.name} 远程配置存在`);
            // 检查URL格式
            const url = remoteResult.stdout;
            if (url.includes('oauth2')) {
              debugResults.push(`   📍 URL: ${url.replace(/oauth2:[^@]+/, 'oauth2:***')}`);
            } else {
              debugResults.push(`   📍 URL: ${url}`);
            }
          } else {
            debugResults.push(`❌ ${repoConfig.name} 远程配置不存在`);
          }
        }

        // 5. 检查认证状态
        debugResults.push('\n=== 仓库认证检查 ===');
        for (const [repoKey, repoConfig] of Object.entries(this.config.repos)) {
          const authUrl = this.getAuthUrl(repoKey);
          const authResult = await this.runGitCommand(`ls-remote ${authUrl} --heads`);
          
          if (authResult.success) {
            debugResults.push(`✅ ${repoConfig.name} 认证成功`);
            // 检查分支是否存在
            if (authResult.stdout.includes('refs/heads/main') || authResult.stdout.includes('refs/heads/master')) {
              debugResults.push(`   🌿 远程分支存在`);
            } else {
              debugResults.push(`   ⚠️ 远程分支可能不存在`);
            }
          } else {
            debugResults.push(`❌ ${repoConfig.name} 认证失败`);
            debugResults.push(`   💡 错误: ${authResult.error}`);
            
            // 提供具体的诊断建议
            if (authResult.error.includes('Authentication failed')) {
              debugResults.push(`   🔑 可能原因: Token 无效或过期`);
            } else if (authResult.error.includes('Could not resolve host')) {
              debugResults.push(`   🌐 可能原因: 网络连接问题或域名错误`);
            } else if (authResult.error.includes('repository not found')) {
              debugResults.push(`   📦 可能原因: 仓库不存在或无访问权限`);
            }
          }
        }

        // 6. 检查本地更改
        debugResults.push('\n=== 本地更改检查 ===');
        const statusResult = await this.runGitCommand('status --porcelain');
        if (statusResult.success && statusResult.stdout.trim()) {
          const changes = statusResult.stdout.split('\n').length;
          debugResults.push(`📝 有 ${changes} 个文件待提交`);
        } else {
          debugResults.push('📝 没有待提交的更改');
        }

        // 7. 测试推送
        debugResults.push('\n=== 推送测试 ===');
        const testPushResult = await this.testGitCodePush();
        if (testPushResult.success) {
          debugResults.push('✅ GitCode 推送测试成功');
        } else {
          debugResults.push('❌ GitCode 推送测试失败');
          debugResults.push(`   💡 错误: ${testPushResult.error}`);
        }
      }

      await e.reply(debugResults.join('\n'));
      return true;

    } catch (error) {
      await e.reply(`❌ 调试过程异常: ${error.message}`);
      return false;
    }
  }

  // ========== 测试 GitCode 推送 ==========
  async testGitCodePush() {
    try {
      const fs = await import('fs/promises');
      
      // 确保目录存在
      try {
        await fs.access(this.config.pluginDir);
      } catch {
        return { success: false, error: '目录不存在' };
      }

      // 检查是否有待提交的更改
      const statusResult = await this.runGitCommand('status --porcelain');
      if (!statusResult.success || !statusResult.stdout.trim()) {
        // 如果没有更改，创建一个测试文件
        const testFile = join(this.config.pluginDir, `test-${Date.now()}.txt`);
        await fs.writeFile(testFile, `测试文件 - ${new Date().toLocaleString('zh-CN')}`);
      }

      // 添加并提交
      await this.runGitCommand('add .');
      const commitResult = await this.runGitCommand(`commit -m "测试提交 ${new Date().toLocaleString('zh-CN')}"`);
      
      if (!commitResult.success) {
        return { success: false, error: '提交失败: ' + commitResult.error };
      }

      // 推送到 GitCode
      const authUrl = this.getAuthUrl('gitcode');
      const pushResult = await this.runGitCommand(`push ${authUrl} main`);
      
      if (pushResult.success) {
        return { success: true, message: '推送成功' };
      } else {
        return { success: false, error: pushResult.error };
      }

    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // ========== 强制推送功能 ==========
  async handleForcePush(e) {
    if (!this.checkAuthPermission(e)) {
      return false;
    }

    try {
      await e.reply('🚨 开始强制推送风云插件到所有仓库...\n⚠️ 注意：这将覆盖远程仓库的所有更改！');
      
      const result = await this.forcePush();

      if (result.success) {
        const noteMsg = `✅ 风云插件强制推送成功\n📝 ${result.message}\n⏰ ${new Date().toLocaleString('zh-CN')}`;
        await this.sendNote(e, noteMsg);
      } else {
        await e.reply('❌ 强制推送失败: ' + result.error);
      }

      return true;

    } catch (error) {
      await e.reply('❌ 强制推送异常: ' + error.message);
      return false;
    }
  }

  // ========== 强制推送Git操作 ==========
  async forcePush() {
    try {
      const fs = await import('fs/promises');
      
      // 确保目录存在
      try {
        await fs.access(this.config.pluginDir);
      } catch {
        await fs.mkdir(this.config.pluginDir, { recursive: true });
      }

      // 初始化Git仓库（如果需要）
      if (!await this.isGitRepository()) {
        await this.runGitCommand('init');
        await this.runGitCommand('checkout -b main');
        await this.runGitCommand('config user.name "风云"');
        await this.runGitCommand('config user.email "597213981@qq.com"');
      }

      // 设置多远程仓库
      await this.setupMultipleRemotes();

      // 添加文件并提交
      await this.runGitCommand('add .');
      
      const status = await this.runGitCommand('status --porcelain');
      if (!status.stdout.trim()) {
        return { success: true, message: '没有检测到文件更改' };
      }

      const commitMsg = `强制推送更新 ${new Date().toLocaleString('zh-CN')}`;
      await this.runGitCommand(`commit -m "${commitMsg}"`);

      // 强制推送到所有远程仓库
      const pushResults = [];
      for (const [repoKey, repoConfig] of Object.entries(this.config.repos)) {
        try {
          const authUrl = this.getAuthUrl(repoKey);
          const pushResult = await this.runGitCommand(`push --force -u ${authUrl} main`);
          if (pushResult.success) {
            pushResults.push(`${repoConfig.name} ✅`);
          } else {
            pushResults.push(`${repoConfig.name} ❌: ${pushResult.error}`);
          }
        } catch (error) {
          pushResults.push(`${repoConfig.name} ❌: ${error.message}`);
        }
      }

      const files = await this.getFileList();
      return {
        success: true,
        message: `强制推送了 ${files.length} 个文件\n推送结果: ${pushResults.join(' | ')}\n提交信息: ${commitMsg}`,
        fileCount: files.length
      };

    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // ========== 更新功能 ==========
  async handleUpdate(e) {
    try {
      await this.sendNoteWithRetry(e, '🔍 风云插件正在检查更新...', 2);

      const result = await this.executeUpdate();
      
      if (!result.success) {
        await this.sendNoteWithRetry(e, `❌ 更新失败：${result.error}`, 2);
        return false;
      }

      if (!result.hasUpdate) {
        await this.sendNoteWithRetry(e, '✅ 风云插件已是最新版本，无需更新', 2);
        return true;
      }

      const noteMsg = `🚀 风云插件更新成功\n📝 ${result.updateLog}\n⏰ ${new Date().toLocaleString('zh-CN')}`;
      await this.sendNoteWithRetry(e, noteMsg, 2);
      
      await this.restartWithRestart(e);
      
      return true;

    } catch (error) {
      await this.sendNoteWithRetry(e, `❌ 更新失败：${error.message}`, 2);
      return false;
    }
  }

  // ========== 推送功能 ==========
  async handlePush(e) {
    if (!this.checkAuthPermission(e)) {
      return false;
    }

    try {
      const commitMessage = this.extractCommitMessage(e);
      const pushType = commitMessage ? '自定义提交' : '自动提交';
      
      await e.reply(`🚀 开始推送风云插件到所有仓库...\n📝 提交类型: ${pushType}\n🔄 推送顺序: GitCode → Gitee`);

      const result = await this.smartPush(commitMessage);

      if (result.success) {
        const noteMsg = `✅ 风云插件推送成功\n📝 ${result.message}\n⏰ ${new Date().toLocaleString('zh-CN')}`;
        await this.sendNote(e, noteMsg);
      } else {
        await e.reply('❌ 推送失败: ' + result.error);
      }

      return true;

    } catch (error) {
      await e.reply('❌ 推送异常: ' + error.message);
      return false;
    }
  }

  // ========== 重启功能 ==========
  async restartWithRestart(e) {
    try {
      await e.reply('🔄 风云插件更新完成，正在重启bot...');
      
      setTimeout(() => {
        try {
          new Restart(e).restart();
        } catch (error) {
          console.error(`${this.logPrefix} 重启失败:`, error);
        }
      }, 2000);
      
    } catch (error) {
      await e.reply(`⚠️ 重启失败: ${error.message}\n💡 请手动重启bot`);
    }
  }

  // ========== 消息发送（带重试） ==========
  async sendNote(e, message) {
    try {
      if (typeof e?.reply === 'function') {
        await e.reply(message);
        
        if (e.isGroup) {
          console.log(`${this.logPrefix} 已发送推送至群 ${e.group_id}`);
        } else {
          console.log(`${this.logPrefix} 已发送推送至用户 ${e.user_id}`);
        }
      }
      
      console.log(`${this.logPrefix} 推送内容: ${message}`);
      
    } catch (error) {
      console.error(`${this.logPrefix} 推送失败:`, error);
      await e.reply(message);
    }
  }

  async sendNoteWithRetry(e, message, maxRetries = 3) {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        await e.reply(message);
        console.log(`${this.logPrefix} 消息发送成功 (尝试 ${attempt})`);
        return true;
      } catch (error) {
        console.error(`${this.logPrefix} 消息发送失败 (尝试 ${attempt}/${maxRetries}):`, error.message);
        
        if (attempt === maxRetries) {
          console.error(`${this.logPrefix} 所有重试尝试均失败`);
          return false;
        }
        
        await this.sleep(2000 * attempt);
      }
    }
    return false;
  }

  // ========== 辅助功能 ==========
  async checkPushStatus(e) {
    if (!this.checkAuthPermission(e)) {
      return false;
    }

    try {
      const status = await this.getSmartStatus();
      
      let msg = '📊 风云插件状态:\n';
      msg += '📍 目录: ' + this.config.pluginDir + '\n';
      msg += '📍 存在: ' + (status.dirExists ? '✅' : '❌') + '\n';
      
      if (status.dirExists) {
        msg += '🔗 Git仓库: ' + (status.isGitRepo ? '✅' : '❌') + '\n';
        
        if (status.isGitRepo) {
          msg += '🌿 分支: ' + status.branch + '\n';
          msg += '📡 远程仓库状态:\n';
          
          for (const [repoKey, repoStatus] of Object.entries(status.remoteStatus || {})) {
            msg += `  • ${repoStatus.name}: ${repoStatus.exists ? '✅' : '❌'}`;
            if (repoStatus.exists) {
              msg += repoStatus.authValid ? ' 🔐' : ' 🔒';
            }
            msg += '\n';
          }
          
          msg += '📝 本地更改: ' + (status.hasChanges ? '✅' : '❌') + '\n';
          msg += '📁 文件数量: ' + status.fileCount + ' 个\n';
          msg += '🔄 更新源: ' + this.config.defaultUpdateSource;
        }
      }

      await e.reply(msg);
      return true;

    } catch (error) {
      await e.reply('❌ 检查状态失败: ' + error.message);
      return false;
    }
  }

  async showHelp(e) {
    if (!this.checkAuthPermission(e)) {
      return false;
    }

    const helpMsg = `📖 风云插件管理器使用说明：

🔄 更新命令：
• #风云更新 - 从GitCode仓库拉取最新代码，更新后自动重启框架
• #风云强制更新 - 强制更新（丢弃所有本地修改）

📤 推送命令：
• #风云推送 - 普通推送（自动提交信息）
• #风云推送 提交说明 - 普通推送（自定义提交信息）
• #风云强制推送 - 强制推送（覆盖远程仓库）

🔧 调试命令：
• #风云调试推送 - 诊断GitCode推送问题

📊 状态命令：
• #风云推送状态 - 查看Git状态

💡 特性：
• 更新优先使用 GitCode 仓库
• 推送同时推送到 GitCode 和 Gitee
• 自动管理多远程仓库
• 仅授权用户可使用
• 通用目录适配（当前目录: ${this.config.pluginDir}）

🔗 仓库信息：
• GitCode: ${this.config.repos.gitcode.url}
• Gitee: ${this.config.repos.gitee.url}`;

    await e.reply(helpMsg);
    return true;
  }

  // ========== 核心Git操作 ==========
  async executeUpdate() {
    try {
      const fs = await import('fs/promises');
      
      try {
        await fs.access(this.config.pluginDir);
      } catch {
        return { success: false, error: '插件目录不存在: ' + this.config.pluginDir, hasUpdate: false };
      }

      if (!await this.isGitRepository()) {
        return { 
          success: true, 
          hasUpdate: true, 
          updateLog: '🎉 首次使用，请先进行推送初始化' 
        };
      }

      await this.setupMultipleRemotes();

      const currentCommit = await this.getCurrentCommit();
      
      let pullSuccess = false;
      let updateSource = this.config.defaultUpdateSource;
      
      try {
        await this.runGitCommand('config pull.rebase false');
        await this.runGitCommand(`fetch ${this.config.defaultUpdateSource}`);
        await this.runGitCommand(`reset --hard ${this.config.defaultUpdateSource}/${this.config.branch}`);
        pullSuccess = true;
      } catch (error) {
        console.log(`${this.logPrefix} GitCode更新失败，尝试Gitee:`, error.message);
        try {
          await this.runGitCommand('fetch gitee');
          await this.runGitCommand('reset --hard gitee/main');
          pullSuccess = true;
          updateSource = 'gitee';
        } catch (fallbackError) {
          return { success: false, error: `更新失败: ${error.message} | 备用更新也失败: ${fallbackError.message}`, hasUpdate: false };
        }
      }
      
      if (!pullSuccess) {
        return { success: false, error: '所有更新源均失败', hasUpdate: false };
      }

      const newCommit = await this.getCurrentCommit();
      if (currentCommit === newCommit) {
        return { success: true, hasUpdate: false, updateSource };
      }
      
      const updateLog = await this.getUpdateLog(currentCommit, newCommit);
      return { success: true, hasUpdate: true, updateLog, updateSource };

    } catch (error) {
      return { success: false, error: error.message, hasUpdate: false };
    }
  }

  async smartPush(commitMessage = null) {
    try {
      const fs = await import('fs/promises');
      
      try {
        await fs.access(this.config.pluginDir);
      } catch {
        await fs.mkdir(this.config.pluginDir, { recursive: true });
      }

      if (!await this.isGitRepository()) {
        await this.runGitCommand('init');
        await this.runGitCommand('checkout -b main');
        await this.runGitCommand('config user.name "风云"');
        await this.runGitCommand('config user.email "597213981@qq.com"');
      }

      await this.setupMultipleRemotes();

      await this.runGitCommand('add .');
      
      const status = await this.runGitCommand('status --porcelain');
      if (!status.stdout.trim()) {
        return { success: true, message: '没有检测到文件更改' };
      }

      const commitMsg = commitMessage || `自动提交 ${new Date().toLocaleString('zh-CN')}`;
      await this.runGitCommand(`commit -m "${commitMsg}"`);

      const pushResults = [];
      for (const [repoKey, repoConfig] of Object.entries(this.config.repos)) {
        try {
          const authUrl = this.getAuthUrl(repoKey);
          const pushResult = await this.runGitCommand(`push -u ${authUrl} main`);
          if (pushResult.success) {
            pushResults.push(`${repoConfig.name} ✅`);
          } else {
            pushResults.push(`${repoConfig.name} ❌: ${pushResult.error}`);
          }
        } catch (error) {
          pushResults.push(`${repoConfig.name} ❌: ${error.message}`);
        }
      }

      const files = await this.getFileList();
      return {
        success: true,
        message: `推送了 ${files.length} 个文件\n推送结果: ${pushResults.join(' → ')}\n提交信息: ${commitMsg}`,
        fileCount: files.length
      };

    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // ========== 多仓库支持方法 ==========
  async setupMultipleRemotes() {
    for (const [repoKey, repoConfig] of Object.entries(this.config.repos)) {
      try {
        await this.runGitCommand(`remote get-url ${repoKey}`);
      } catch {
        await this.runGitCommand(`remote add ${repoKey} ${repoConfig.url}`);
      }
    }
  }

  getAuthUrl(repoKey) {
    const repoConfig = this.config.repos[repoKey];
    if (!repoConfig) {
      throw new Error(`未知的仓库配置: ${repoKey}`);
    }
    
    const url = new URL(repoConfig.url);
    const domain = url.hostname;
    const path = url.pathname;
    
    return `https://oauth2:${repoConfig.token}@${domain}${path}`;
  }

  // ========== 工具方法 ==========
  extractCommitMessage(e) {
    const match = e.msg.match(/^#风云推送\s+(.+)$/);
    return match?.[1]?.trim() || null;
  }

  async runGitCommand(cmd) {
    const { exec } = await import('child_process');
    return new Promise((resolve) => {
      exec(`git ${cmd}`, { 
        cwd: this.config.pluginDir,
        timeout: 60000 
      }, (error, stdout, stderr) => {
        if (error) {
          resolve({ success: false, error: stderr || error.message });
        } else {
          resolve({ success: true, stdout: stdout.trim() });
        }
      });
    });
  }

  async isGitRepository() {
    try {
      const fs = await import('fs/promises');
      await fs.access(`${this.config.pluginDir}/.git`);
      return true;
    } catch {
      return false;
    }
  }

  async getCurrentCommit() {
    try {
      const result = await this.runGitCommand('rev-parse HEAD');
      return result.success ? result.stdout : null;
    } catch {
      return null;
    }
  }

  async getUpdateLog(oldCommit, newCommit) {
    try {
      if (!oldCommit) return '🎉 首次安装风云插件';

      const result = await this.runGitCommand(`log ${oldCommit}..${newCommit} --oneline --no-merges`);
      if (result.success && result.stdout.trim()) {
        return result.stdout.split('\n')
          .map(line => `• ${line}`)
          .join('\n');
      }
      return '🔄 插件已更新到最新版本';
    } catch {
      return '🔄 插件文件已同步到最新版本';
    }
  }

  async getSmartStatus() {
    const fs = await import('fs/promises');
    const status = {
      dirExists: false,
      isGitRepo: false,
      branch: '未知',
      remoteStatus: {},
      hasChanges: false,
      fileCount: 0
    };

    try {
      await fs.access(this.config.pluginDir);
      status.dirExists = true;
      
      status.isGitRepo = await this.isGitRepository();
      if (status.isGitRepo) {
        const branchResult = await this.runGitCommand('branch --show-current');
        status.branch = branchResult.success ? branchResult.stdout : '未知';

        for (const [repoKey, repoConfig] of Object.entries(this.config.repos)) {
          const remoteStatus = {
            name: repoConfig.name,
            exists: false,
            authValid: false
          };

          try {
            const remoteResult = await this.runGitCommand(`remote get-url ${repoKey}`);
            remoteStatus.exists = remoteResult.success;

            try {
              const authUrl = this.getAuthUrl(repoKey);
              const authResult = await this.runGitCommand(`ls-remote ${authUrl}`);
              remoteStatus.authValid = authResult.success && authResult.stdout.includes('refs/heads/');
            } catch {
              remoteStatus.authValid = false;
            }
          } catch {
            // 远程不存在
          }

          status.remoteStatus[repoKey] = remoteStatus;
        }

        const changeResult = await this.runGitCommand('status --porcelain');
        status.hasChanges = changeResult.success && changeResult.stdout.trim().length > 0;

        status.fileCount = (await this.getFileList()).length;
      }
    } catch {
      // 状态保持默认值
    }

    return status;
  }

  async getFileList() {
    try {
      const fs = await import('fs/promises');
      const path = await import('path');
      
      const files = [];
      const scanDir = async (dir) => {
        try {
          const items = await fs.readdir(dir);
          for (const item of items) {
            if (item === '.git') continue;
            const fullPath = path.join(dir, item);
            const stat = await fs.stat(fullPath);
            if (stat.isDirectory()) {
              await scanDir(fullPath);
            } else {
              files.push(fullPath);
            }
          }
        } catch {
          // 忽略错误
        }
      };
      
      await scanDir(this.config.pluginDir);
      return files;
    } catch {
      return [];
    }
  }

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}